package com.xauto.pioneer.appuser.activity.takeCar;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.navi.BaiduMapAppNotSupportNaviException;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviParaOption;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.ta.utdid2.android.utils.StringUtils;
import com.xauto.pioneer.appuser.MyApplication;
import com.xauto.pioneer.appuser.R;
import com.xauto.pioneer.appuser.activity.BaseActivity;
import com.xauto.pioneer.appuser.http.BaseLHttpHandler;
import com.xauto.pioneer.appuser.http.LHttpLib;
import com.xauto.pioneer.appuser.model.CarOrderInfo;
import com.xauto.pioneer.appuser.model.JSONStatus;
import com.xauto.pioneer.appuser.model.ParkingSite;
import com.xauto.pioneer.appuser.util.OverlayManager;
import com.xauto.pioneer.appuser.view.TopBar;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.OnClick;

/***
 * 导航页面
 *
 * @author Lemon Fri 24 Feb 18:35
 */
public class NavigationActivity extends BaseActivity {

    @Bind(R.id.topBar)
    TopBar topBar;
    @Bind(R.id.mapMain)
    MapView mMapView;
    @Bind(R.id.park_name_text)
    TextView parkNameText;
    @Bind(R.id.park_info_text)
    TextView parkInfoText;
    @Bind(R.id.nav_text)
    TextView navText;
    /****************
     * 地图相关
     ******************/
    private BaiduMap mBaiDuMap;
    /**
     * 定位相关
     */
    private LocationClient mLocClient;
    boolean isFirstLoc = true; // 是否首次定位
    /**
     * 所有marker集合
     */
    private List<OverlayOptions> overlayOptionsList;
    /**
     * marker 操作管理
     */
    private MyOverlayManager myOverlayManager;
    /**
     * 定位成功后，返回的当前定位
     */
    private BDLocation bdLocation;
    private boolean isOpenRoadStatus = false;
    private DisplayImageOptions hasCarOptions;
    private DisplayImageOptions noCarOptions;
    ParkingSite parkingSite;
    CarOrderInfo carOrderInfo;
    Timer timer = null;
    /**
     * 入口
     *
     * @param mContext
     */
    public static void startAction(Context mContext, ParkingSite parkingSite,CarOrderInfo carOrderInfo) {
        Intent intent = new Intent(mContext, NavigationActivity.class);
        intent.putExtra("parkingSite", parkingSite);
        intent.putExtra("carOrderInfo", carOrderInfo);
        mContext.startActivity(intent);
    }

    @Override
    protected int getContentView() {
        return R.layout.ac_navigation;
    }

    @Override
    protected void initView() {
    }

    @Override
    protected void initData() {
        hasCarOptions = MyApplication.getDisplayImageOptions(mContext, 20, R.mipmap.ic_map_car_blue);
        noCarOptions = MyApplication.getDisplayImageOptions(mContext, 20, R.mipmap.ic_map_car_gray);
        initBaiDuMap();
        parkingSite = (ParkingSite) getIntent().getSerializableExtra("parkingSite");
        carOrderInfo = (CarOrderInfo) getIntent().getSerializableExtra("carOrderInfo");
        topBar.showView(TopBar.LEFT_IMAGE_BTN, TopBar.TITLE);
        topBar.setText(TopBar.TITLE, parkingSite.parking_site_name);
        topBar.setImage(TopBar.LEFT_IMAGE_BTN, R.mipmap.ic_common_left);
        topBar.setLeftOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        getSiteDetail();
    }
    @OnClick(R.id.nav_text)
    public void onViewClicked() {
        navigationEvent();
    }


    private class MyOverlayManager extends OverlayManager {

        private List<OverlayOptions> overlayOptionsList;

        public void setOverlayOptionsList(List<OverlayOptions> overlayOptionsList) {
            this.overlayOptionsList = overlayOptionsList;
        }

        public MyOverlayManager(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public List<OverlayOptions> getOverlayOptions() {
            return overlayOptionsList;
        }

        @Override
        public boolean onMarkerClick(Marker marker) {
            return false;
        }

        @Override
        public boolean onPolylineClick(Polyline polyline) {
            return false;
        }
    }
    /************************************** 百度地图相关配置 ⬆️ *******************************************/
    /**
     * 初始化地图
     */
    private void initBaiDuMap() {
        mBaiDuMap = mMapView.getMap();
        // LocationMode.COMPASS 罗盘 FOLLOWING 跟随 NORMAL 普通
        mBaiDuMap.setMyLocationConfigeration(
//        new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING, true, null, accuracyCircleFillColor, accuracyCircleStrokeColor));
                new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING, true, null)); //传入null当前定位是默认蓝色小点图标
        // 开启定位图层
        mBaiDuMap.setMyLocationEnabled(true);
        // 开启交通路况图
        mBaiDuMap.setTrafficEnabled(isOpenRoadStatus);
        // 定位初始化
        mLocClient = new LocationClient(getApplicationContext());
        mLocClient.registerLocationListener(new MyLocationListener());
        initLocation();
        mLocClient.start();
        myOverlayManager = new MyOverlayManager(mBaiDuMap);
        mBaiDuMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                //TODO 点击地图标注
                Bundle info = marker.getExtraInfo();
                ParkingSite parkingSite = (ParkingSite) info.getSerializable("parkingSite");
                return true;
            }
        });
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            bdLocation = location;
            if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
                addMarker();
            }
            // 构造定位数据
            MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude()).longitude(location.getLongitude()).build();
            mBaiDuMap.setMyLocationData(locData); // 设置定位数据
            mBaiDuMap.setMaxAndMinZoomLevel(19, 10);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(14);
                mBaiDuMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
            mBaiDuMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {
                @Override
                public void onMapLoaded() {
                    myOverlayManager = new MyOverlayManager(mBaiDuMap);
                }
            });
            mBaiDuMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
                @Override
                public void onMapStatusChangeStart(MapStatus mapStatus) {

                }
                @Override
                public void onMapStatusChangeStart(MapStatus arg0, int arg1) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onMapStatusChange(MapStatus mapStatus) {

                }

                @Override
                public void onMapStatusChangeFinish(MapStatus mapStatus) {
                    if (mapStatus.zoom <= 14) {
                    }
                }
            });
            logLocationData(location);
        }


        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

    /**
     * 初始化定位设置
     */
    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");
        //可选，默认gcj02，设置返回的定位结果坐标系
        int span = 0;//1000 //todo 根据实际情况是否关闭定位，暂时只定位一次
        //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setScanSpan(span);
        //可选，设置是否需要地址信息，默认不需要
        option.setIsNeedAddress(true);
        //可选，默认false,设置是否使用gps
        option.setOpenGps(true);
        //可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setLocationNotify(true);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationDescribe(true);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIsNeedLocationPoiList(true);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.setIgnoreKillProcess(false);
        //可选，默认false，设置是否收集CRASH信息，默认收集
        option.SetIgnoreCacheException(false);
        //可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        option.setEnableSimulateGps(false);
        // 在网络定位中，获取手机机头所指的方向
        option.setNeedDeviceDirect(true);
        mLocClient.setLocOption(option);
    }

    /**
     * 地图打点
     */
    void addMarker() {
        overlayOptionsList = new ArrayList<>();
        final View v = LayoutInflater.from(this).inflate(R.layout.item_parking_space_marker, null);
        final ImageView ivMapParkingSite = (ImageView) v.findViewById(R.id.ivMapParkingSite);
        TextView tvMapUsableCarCount = (TextView) v.findViewById(R.id.tvMapUsableCarCount);
        TextView tvMapUsableCarCountName = (TextView) v.findViewById(R.id.tvMapUsableCarCountName);
        tvMapUsableCarCount.setText(String.valueOf(parkingSite.usable_space_count));
        tvMapUsableCarCountName.setText(parkingSite.parking_site_name+","+String.valueOf(parkingSite.usable_space_count)+"车位");
        if (StringUtils.isEmpty(parkingSite.parking_site_image.thumb)){
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(new LatLng(parkingSite.latitude_num, parkingSite.longitude_num));
            markerOptions.icon(BitmapDescriptorFactory.fromView(v));
            Bundle info = new Bundle();
            info.putSerializable("parkingSite", parkingSite);
            markerOptions.extraInfo(info);
            overlayOptionsList.add(markerOptions);
            showMarkerView();
        }else {
            imageLoader.displayImage(parkingSite.parking_site_image.thumb, ivMapParkingSite,
                    parkingSite.usable_car_count > 0 ? hasCarOptions : noCarOptions, new ImageLoadingListener() {
                        @Override
                        public void onLoadingStarted(String s, View view) {

                        }

                        @Override
                        public void onLoadingFailed(String s, View view, FailReason failReason) {
                            MarkerOptions markerOptions = new MarkerOptions();
                            markerOptions.position(new LatLng(parkingSite.latitude_num, parkingSite.longitude_num));
                            markerOptions.icon(BitmapDescriptorFactory.fromView(v));
                            Bundle info = new Bundle();
                            info.putSerializable("parkingSite", parkingSite);
                            markerOptions.extraInfo(info);
                            overlayOptionsList.add(markerOptions);
                            showMarkerView();
                        }

                        @Override
                        public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                            MarkerOptions markerOptions = new MarkerOptions();
                            markerOptions.position(new LatLng(parkingSite.latitude_num, parkingSite.longitude_num));
                            markerOptions.icon(BitmapDescriptorFactory.fromView(v));
                            Bundle info = new Bundle();
                            info.putSerializable("parkingSite", parkingSite);
                            markerOptions.extraInfo(info);
                            ivMapParkingSite.setImageBitmap(bitmap);
                            overlayOptionsList.add(markerOptions);
                            showMarkerView();
                        }

                        @Override
                        public void onLoadingCancelled(String s, View view) {

                        }
                    });

//            }
        }


    }
    private void showMarkerView(){
        if (overlayOptionsList != null && overlayOptionsList.size() > 0) {
            if (!overlayOptionsList.equals(myOverlayManager.getOverlayOptions())) {
                myOverlayManager.removeFromMap();
                myOverlayManager.setOverlayOptionsList(overlayOptionsList);
                myOverlayManager.addToMap();
                myOverlayManager.zoomToSpan();
            }
        }
    }
    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        mMapView.requestFocus();
        mLocClient.start();
        mBaiDuMap.setMyLocationEnabled(true);
        super.onResume();
    }
    @Override
    protected void onStop() {
        super.onStop();
        mBaiDuMap.setMyLocationEnabled(false);
        mLocClient.stop();
    }
    @Override
    protected void onDestroy() {
        timer.cancel();
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiDuMap.setMyLocationEnabled(false);
        mBaiDuMap.clear();
        mMapView.onDestroy();
        mMapView = null;
        mBaiDuMap = null;
        super.onDestroy();
    }

    private void logLocationData(BDLocation location) {
        //获取定位结果
        StringBuffer sb = new StringBuffer(256);
        sb.append("time : ");
        sb.append(location.getTime());    //获取定位时间
        sb.append("\nerror code|location type : ");
        sb.append(location.getLocType());    //获取类型类型
        sb.append("\nlatitude : ");
        sb.append(location.getLatitude());    //获取纬度信息
        sb.append("\nlontitude : ");
        sb.append(location.getLongitude());    //获取经度信息
        sb.append("\nradius : ");
        sb.append(location.getRadius());    //获取定位精准度
        if (location.getLocType() == BDLocation.TypeGpsLocation) {
            // GPS定位结果
            sb.append("\nspeed : ");
            sb.append(location.getSpeed());    // 单位：公里每小时
            sb.append("\nsatellite : ");
            sb.append(location.getSatelliteNumber());    //获取卫星数
            sb.append("\nheight : ");
            sb.append(location.getAltitude());    //获取海拔高度信息，单位米
            sb.append("\ndirection : ");
            sb.append(location.getDirection());    //获取方向信息，单位度
            sb.append("\naddr : ");
            sb.append(location.getAddrStr());    //获取地址信息
            sb.append("\ndescribe : ");
            sb.append("gps定位成功");
        } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
            // 网络定位结果
            sb.append("\naddr : ");
            sb.append(location.getAddrStr());    //获取地址信息
            sb.append("\noperationers : ");
            sb.append(location.getOperators());    //获取运营商信息
            sb.append("\ndirection : ");
            sb.append(location.getDirection()); //获得手机方向，范围【0-360】，手机上部正朝向北的方向为0°方向
            sb.append("\ndescribe : ");
            sb.append("网络定位成功");
        } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {
            // 离线定位结果
            sb.append("\ndescribe : ");
            sb.append("离线定位成功，离线定位结果也是有效的");
        } else if (location.getLocType() == BDLocation.TypeServerError) {
            sb.append("\ndescribe : ");
            sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
        } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
            sb.append("\ndescribe : ");
            sb.append("网络不同导致定位失败，请检查网络是否通畅");
        } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
            sb.append("\ndescribe : ");
            sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
        }
        sb.append("\nlocationdescribe : ");
        sb.append(location.getLocationDescribe());    //位置语义化信息
        List<Poi> list = location.getPoiList();    // POI数据
        if (list != null) {
            sb.append("\npoilist size = : ");
            sb.append(list.size());
            for (Poi p : list) {
                sb.append("\npoi= : ");
                sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
            }
        }
        Log.e(TAG, sb.toString());
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }
   private void getSiteDetail(){
       timer = new Timer();
       //每隔30秒执行一次
       timer.schedule(new TimerTask() {
           @Override
           public void run() {
           new LHttpLib().getReturnParkingSiteDetail(mContext,memberId,carOrderInfo.car_order_no,
                   bdLocation.getLongitude(),bdLocation.getLatitude(),parkingSite.parking_site_no,new BaseLHttpHandler(mContext,false,false){
                       @Override
                       public void onSuccess(final JSONStatus jsonStatus) {
                           super.onSuccess(jsonStatus);
                           runOnUiThread(new Runnable() {
                               @Override
                               public void run() {
                                   ParkingSite parkingSite  = new ParkingSite().parse(jsonStatus.data.optJSONObject("parking_site_info"));
                                   //显示相关数据
                                   topBar.setText(TopBar.TITLE, parkingSite.parking_site_name);
                                   parkNameText.setText(parkingSite.parking_site_name);
                                   parkInfoText.setText(parkingSite.usable_space_count+"车位");
                               }
                           });
                       }
                   });

           }
       },1000,1000*30);
   }
    /**
     * 导航事件
     */
    private void navigationEvent(){
        NaviParaOption para = new NaviParaOption();
        para.startName("");
        para.startPoint(new LatLng(bdLocation.getLatitude(),bdLocation.getLongitude()));
        para.endName(parkingSite.parking_site_name);
        para.endPoint(new LatLng(parkingSite.latitude_num,parkingSite.latitude_num));

        try {

            BaiduMapNavigation.openBaiduMapNavi(para, this);

        } catch (BaiduMapAppNotSupportNaviException e) {
            e.printStackTrace();
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("您尚未安装百度地图app或app版本过低，点击确认安装？");
            builder.setTitle("提示");
            builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
//                    BaiduMapNavigation.getLatestBaiduMapApp(NavigationActivity.this);
                }
            });

            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            builder.create().show();
        }
    }
}
